package com.livestocksolutions.intent;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.livestocksolutions.Acquisition;
import com.livestocksolutions.Bovine;
import com.livestocksolutions.Bull;
import com.livestocksolutions.Business;
import com.livestocksolutions.CattleBreed;
import com.livestocksolutions.Cow;
import com.livestocksolutions.Eartag;
import com.livestocksolutions.FeedHistory;
import com.livestocksolutions.Group;
import com.livestocksolutions.Join;
import com.livestocksolutions.LivestockSolutions;
import com.livestocksolutions.MedicalHistory;
import com.livestocksolutions.MedicineHistory;
import com.livestocksolutions.Mob;
import com.livestocksolutions.Observation;

import com.livestocksolutions.R;
import com.livestocksolutions.ui.ListCattleArrayAdapter;
import com.livestocksolutions.ui.ListGroupArrayAdapter;
import com.livestocksolutions.ui.ListGroupMobArrayAdapter;
import com.livestocksolutions.ui.ListJoinArrayAdapter;
import com.livestocksolutions.ui.ListMedicalHistoryArrayAdapter;
import com.livestocksolutions.ui.ListObservationArrayAdapter;
import com.livestocksolutions.ui.ListUsableItemHistoryArrayAdapter;
import com.livestocksolutions.ui.ViewCattleArrayAdapter;
import com.livestocksolutions.ui.ViewGroupMobArrayAdapter;
import com.livestocksolutions.ui.ViewJoinArrayAdapter;
import com.livestocksolutions.ui.ViewObservationArrayAdapter;
import com.livestocksolutions.util.StringArrayParcelable;

/* -- Version History --
 *  1.0 : 10 September 2012 - Initial version.
 *  
 *  1.1 : 04 October 2012   - Allowed new Cattle with no dob, removed assumption that dame or sire must be at
 *                            least gestation period length and have reached pubity
 */

/**
 * A class to create the layout for a Bovine
 * @author Adam Parr
 * @version 1.0
 * 
 * @.modified 18 October 2012
 */
public class BovineActivity extends BaseActivity {
	public static final int BOVINEVIEW 		 = 0;
	public static final int CATTLEVIEW 		 = 1;
	public static final int GROUPVIEW 		 = 2;
	public static final int MEDICINEVIEW 		 = 3;
	public static final int MEDICALVIEW 		 = 4;
	public static final int FEEDVIEW 			 = 5;
	public static final int JOINVIEW 			 = 6;
	
	/**
	 * Stores the reference to the XML layout template for each view
	 * @see #BOVINEVIEW
	 * @see #CATTLEVIEW
	 * @see #GROUPVIEW
	 * @see #MEDICINEVIEW
	 * @see #MEDICALVIEW
	 * @see #FEEDVIEW
	 * @see #JOINVIEW
	 */
	public static final Integer[] RESOURCEID = new Integer[]{
		R.layout.item,
		R.layout.item,
		R.layout.item,
		R.layout.item,
		R.layout.item,
		R.layout.item,
		R.layout.item
	};
	
	/**
	 *  Cattle View that holds the data of the Bovine
	 */
	protected ViewCattleArrayAdapter bovineView;
	/**
	 * List of Group that holds the groups the Bovine is in
	 */
	protected ListGroupArrayAdapter groupList;
	/**
	 * List of Cattle that holds the offspring for this Bovine
	 */
	protected ListCattleArrayAdapter cattleList;
	/**
	 * List of Observations that holds the Observations of the Group
	 */
	protected ListObservationArrayAdapter observationList;
	/**
	 * List of Joins that holds the Joining of the Mob
	 */
	protected ListJoinArrayAdapter joinList;
	/**
	 * Lest of Vet Visits.
	 */
	protected ListMedicalHistoryArrayAdapter medicalList;
	/**
	 * List of medicines administered to this Bovine.
	 */
	protected ListUsableItemHistoryArrayAdapter medicineList;
	/**
	 * List of Feeds given to this Bovine.
	 */
	protected ListUsableItemHistoryArrayAdapter feedList;
	
	/**
	 * ID of the Sire of this Bovine.
	 */
	protected long sire = 0;
	
	/**
	 * ID of the Dame of this Bovine.
	 */
	protected long dame = 0;
	
	/**
	 * ID of the Mob that this Bovine is in.
	 */
	protected long mob = 0;
	
	/**
	 * Constructor
	 */
	public BovineActivity() {
		super(RESOURCEID);
	}
	
	protected BovineActivity(Integer[] resourceIds) {
		super(resourceIds);
	}
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
    	super.create(savedInstanceState);
        
    	if(stack.size()==0){
    		setContentView(RESOURCEID[BOVINEVIEW]);
    		
    		if(!built){
    			LinearLayout view = (LinearLayout) findViewById(R.id.listView);
    			view.removeAllViews();
    			view.addView(getLoading(view));
    		//	bovineView = new ViewCattleArrayAdapter(null, null);
    			new LoadData().execute(null, null, null);
    			
				currentState.putInt(STATEID,BOVINEVIEW);
    		}
    	}
    }
	
    /**
     * Loads the initial data on a separate thread so that the UI thread is not
     * frozen for a long period of time.
     * @author Adam Parr
     * @.modified 28 September 2012
     */
    private class LoadData extends AsyncTask<String, Integer, Long> {
        @Override
		protected Long doInBackground(String... strings) {
        	String[] cattleType = new String[ViewCattleArrayAdapter.SIZE];
    		String[][] cattleValues = new String[][]{};
    		String[][] groupValues = new String[][]{};
    		String[][] observationValues = new String[][]{};
			String[][] joinValues = new String[][]{};
			String[][] medicalValues = new String[][]{};
			String[][] medcineValues = new String[][]{};
			String[][] feedValues = new String[][]{};
			// Put the ID of this Bovine Object
            id = id!=-1?id:getIntent().getExtras().getLong(ITEMID,-1);
            Bovine b = LivestockSolutions.getBovineByID(id);
			if(b==null){
				edit = true;
				cattleType[ViewCattleArrayAdapter.ID]=String.valueOf(id);
				cattleType[ViewCattleArrayAdapter.DOB]=String.valueOf(new Date().getTime());
				cattleType[ViewCattleArrayAdapter.WITHHOLD]=String.valueOf(new Date().getTime());
				cattleType[ViewCattleArrayAdapter.ACTIVE]=String.valueOf(true);
				if(id!=-1 || LivestockSolutions.getBreeds().length == 0){
	    			empty=true;
	    			edit=false;
	    		}
			}else{
    			// Read initial state of the Location Object and add to locationType and observationValues
    			Date slaughterDate =  b.getSafeSlaughterDate();
    			CattleBreed breed = b.getBreed();
    			Bovine dame = b.getDame();
    			Bovine sire = b.getSire();
    			Mob mob = b.getBelongingMob();
    			Date dob = b.getDob();
    			
    			BovineActivity.this.sire=sire!=null?sire.getID():0;
    			BovineActivity.this.dame=dame!=null?dame.getID():0;
    			BovineActivity.this.mob=mob!=null?mob.getID():0;
    			
    			cattleType[ViewCattleArrayAdapter.ID]=String.valueOf(b.getID());
    			cattleType[ViewCattleArrayAdapter.VISUALID]=b.getEartag().getEartagID();
    			cattleType[ViewCattleArrayAdapter.NLISRFID]=b.getEartag().getRfID();
    			cattleType[ViewCattleArrayAdapter.WITHHOLD]=String.valueOf(slaughterDate!=null?slaughterDate.getTime():"");
    			cattleType[ViewCattleArrayAdapter.NLIS]=b.getEartag().getNlisID();
    			cattleType[ViewCattleArrayAdapter.GENDER]=b.getGender();
    			cattleType[ViewCattleArrayAdapter.BREED]=breed!=null?String.valueOf(breed.getID()):"0";
    			cattleType[ViewCattleArrayAdapter.DOB]=dob!=null?String.valueOf(b.getDob().getTime()):"";
    			cattleType[ViewCattleArrayAdapter.ACTIVE]=String.valueOf(b.isActive());
    			cattleType[ViewCattleArrayAdapter.DAME]=dame!=null?String.valueOf(dame.getID()):"0";
    			cattleType[ViewCattleArrayAdapter.SIRE]=sire!=null?String.valueOf(sire.getID()):"0";
    			cattleType[ViewCattleArrayAdapter.MOB]=mob!=null?String.valueOf(mob.getID()):"0";
    			
    			Bovine[] offspring = b.getOffspring();
    			Arrays.sort(offspring, bovineComparator);
    			cattleValues = new String[offspring.length][ListCattleArrayAdapter.SIZE];
    			int y=0;
    			for(int x=0; x<offspring.length; x++){
    				Date sd =  offspring[x].getDob();

    				if(offspring[x]!=null){
	    				cattleValues[y][ViewCattleArrayAdapter.ID]=String.valueOf(offspring[x].getID());
	    				cattleValues[y][ViewCattleArrayAdapter.VISUALID]=offspring[x].getEartag().getEartagID();
	    				cattleValues[y][ViewCattleArrayAdapter.NLISRFID]=offspring[x].getEartag().getRfID();
	    				cattleValues[y][ViewCattleArrayAdapter.DOB]=sd!=null?String.valueOf(sd.getTime()):"";
	    				y++;
    				}
    			}
    			
    			Group[] groups = b.getGroups();
    			Arrays.sort(groups, groupComparator);
    			groupValues = new String[groups.length][ViewGroupMobArrayAdapter.SIZE];
    			for(int x=0; x<groups.length; x++){
    				groupValues[x][ViewGroupMobArrayAdapter.ID]=String.valueOf(groups[x].getID());
    				groupValues[x][ViewGroupMobArrayAdapter.NAME]=groups[x].getName();
    				groupValues[x][ListGroupMobArrayAdapter.COUNT]=String.valueOf(groups[x].getBovineList().length);
    			}
    			
    			Observation[] observations = b.getObservations();
    			Arrays.sort(observations, observationComparator);
    			observationValues = new String[observations.length][ViewObservationArrayAdapter.SIZE];
    			for(int x=0; x<observations.length; x++){
    				observationValues[x][ViewObservationArrayAdapter.ID]=String.valueOf(observations[x].getID());
    				observationValues[x][ViewObservationArrayAdapter.DATE]=String.valueOf(observations[x].getDate().getTime());
    				observationValues[x][ViewObservationArrayAdapter.TYPE]=String.valueOf(observations[x].getPriority());
    				observationValues[x][ViewObservationArrayAdapter.VALUE]=observations[x].getComment();
    			}
    			
    			Join[] joins = b.getJoinings();
    			Arrays.sort(joins, joinComparator);
    			joinValues = new String[joins.length][ViewJoinArrayAdapter.SIZE];
    			for(int x=0; x<joins.length; x++){
    				Date id =  joins[x].getInsertionDate();
    				Date rd =  joins[x].getRemovalDate();
    				
    				joinValues[x][ViewJoinArrayAdapter.ID]=String.valueOf(joins[x].getID());
    				joinValues[x][ViewJoinArrayAdapter.INSERTIONDATE]=id!=null?String.valueOf(id.getTime()):"";
    				joinValues[x][ViewJoinArrayAdapter.REMOVALDATE]=rd!=null?String.valueOf(rd.getTime()):"";
    				joinValues[x][ViewJoinArrayAdapter.COUNT]=String.valueOf(joins[x].getCows().length);
    			}
    			
    			MedicalHistory[] medicals = b.getMedicals();
    			Arrays.sort(medicals, medicalHistoryComparator);
    			medicalValues = new String[medicals.length][ListMedicalHistoryArrayAdapter.SIZE];
    			for(int x=0; x<medicals.length; x++){
    				medicalValues[x][ListMedicalHistoryArrayAdapter.ID]=String.valueOf(x);
    				medicalValues[x][ListMedicalHistoryArrayAdapter.VET]=String.valueOf(medicals[x].getVet().getID());
    				medicalValues[x][ListMedicalHistoryArrayAdapter.COST]=String.valueOf(medicals[x].getCost());
    				medicalValues[x][ListMedicalHistoryArrayAdapter.DATE]=medicals[x].getDate()!=null?String.valueOf(medicals[x].getDate().getTime()):"";
    				medicalValues[x][ListMedicalHistoryArrayAdapter.COMMENT]=medicals[x].getComments();
    			}

    			MedicineHistory[] medicines = b.getMedicines();
    			Arrays.sort(medicines, usableItemHistoryComparator);
        		medcineValues = new String[medicines.length][ListUsableItemHistoryArrayAdapter.SIZE];
        		for(int x=0; x<medicines.length; x++){
        			medcineValues[x][ListUsableItemHistoryArrayAdapter.ID]=String.valueOf(medicines[x].getItem().getID());
        			medcineValues[x][ListUsableItemHistoryArrayAdapter.NAME]=medicines[x].getItem().getName();
        			medcineValues[x][ListUsableItemHistoryArrayAdapter.USEDATE]=medicines[x].getDate()!=null?String.valueOf(medicines[x].getDate().getTime()):"";
        			medcineValues[x][ListUsableItemHistoryArrayAdapter.QUANTITY]=String.valueOf(medicines[x].getQuantity());
        			medcineValues[x][ListUsableItemHistoryArrayAdapter.MEASUREMENT]=medicines[x].getMeasurement();
        		}
    			
    			FeedHistory[] feeds = b.getHandFeeds();
    			Arrays.sort(feeds, usableItemHistoryComparator);
            	feedValues = new String[feeds.length][ListUsableItemHistoryArrayAdapter.SIZE];
            	for(int x=0; x<feeds.length; x++){
            		feedValues[x][ListUsableItemHistoryArrayAdapter.ID]=String.valueOf(feeds[x].getItem().getID());
            		feedValues[x][ListUsableItemHistoryArrayAdapter.NAME]=feeds[x].getItem().getName();
            		feedValues[x][ListUsableItemHistoryArrayAdapter.USEDATE]=feeds[x].getDate()!=null?String.valueOf(feeds[x].getDate().getTime()):"";
            		feedValues[x][ListUsableItemHistoryArrayAdapter.QUANTITY]=String.valueOf(feeds[x].getQuantity());
            		feedValues[x][ListUsableItemHistoryArrayAdapter.MEASUREMENT]=feeds[x].getMeasurement();
            	}
			}
			bovineView = new ViewCattleArrayAdapter(BovineActivity.this, cattleType);
			groupList = new ListGroupArrayAdapter(BovineActivity.this, groupValues);
			cattleList = new ListCattleArrayAdapter(BovineActivity.this, cattleValues);
			observationList = new ListObservationArrayAdapter(BovineActivity.this, observationValues);
			joinList = new ListJoinArrayAdapter(BovineActivity.this, joinValues);
			medicalList = new ListMedicalHistoryArrayAdapter(BovineActivity.this, medicalValues);
			medicineList = new ListUsableItemHistoryArrayAdapter(BovineActivity.this, medcineValues);
			feedList = new ListUsableItemHistoryArrayAdapter(BovineActivity.this, feedValues);
        	return 0L;
        }
        
        @Override
		protected void onPostExecute(Long returned) {
	        setPage();
	        constructFrame(currentState.getInt(STATEID));
	        built=true;
        }
    }
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	// Show the menu for the Bovine Object
        getMenuInflater().inflate(R.menu.cattle_menu, menu);
        this.menu=menu;
        return true;
    }
    
    @Override
    public void onSaveInstanceState (Bundle outState) {
    	super.onSaveInstanceState (outState);

    	outState.putParcelable("bovineType", new StringArrayParcelable().setStrings(bovineView.get()));
    	outState.putParcelable("bovineJoin", new StringArrayParcelable().setStrings(joinList.get()));
    	outState.putParcelable("bovineGroup", new StringArrayParcelable().setStrings(groupList.get()));
    	outState.putParcelable("bovineOffspring", new StringArrayParcelable().setStrings(cattleList.get()));
    	outState.putParcelable("bovineObservation", new StringArrayParcelable().setStrings(observationList.get()));
    	outState.putParcelable("bovineMedical", new StringArrayParcelable().setStrings(medicalList.get()));
    	outState.putParcelable("bovineMedicine", new StringArrayParcelable().setStrings(medicineList.get()));
    	outState.putParcelable("bovineFeed", new StringArrayParcelable().setStrings(feedList.get()));
    	
    	outState.putLong("sire", sire);
    	outState.putLong("dame", dame);
    	outState.putLong("mob", mob);
    }
    
    @Override
    public void onRestoreInstanceState(Bundle inState) {
    	bovineView = new ViewCattleArrayAdapter(this,((StringArrayParcelable)inState.getParcelable("bovineType")).getStrings()[0]);
    	joinList = new ListJoinArrayAdapter(this,((StringArrayParcelable)inState.getParcelable("bovineJoin")).getStrings());
    	groupList = new ListGroupArrayAdapter(this,((StringArrayParcelable)inState.getParcelable("bovineGroup")).getStrings());
    	cattleList = new ListCattleArrayAdapter(this,((StringArrayParcelable)inState.getParcelable("bovineOffspring")).getStrings());
    	observationList = new ListObservationArrayAdapter(this,((StringArrayParcelable)inState.getParcelable("bovineObservation")).getStrings());
    	medicalList = new ListMedicalHistoryArrayAdapter(this,((StringArrayParcelable)inState.getParcelable("bovineMedical")).getStrings());
    	medicineList = new ListUsableItemHistoryArrayAdapter(this,((StringArrayParcelable)inState.getParcelable("bovineMedicine")).getStrings());
    	feedList = new ListUsableItemHistoryArrayAdapter(this,((StringArrayParcelable)inState.getParcelable("bovineFeed")).getStrings());
    	
    	sire = inState.getLong("sire");
    	dame = inState.getLong("dame");
    	mob = inState.getLong("mob");
    	
    	super.onRestoreInstanceState (inState);
    }
    
    @Override
    public boolean frameSelection(int frame) {
        switch (frame) {
        	case R.id.menu_join:
        		showView(JOINVIEW,currentState);
        		break;
        	case R.id.menu_offspring:
        		showView(CATTLEVIEW,currentState);
        		break;
        	case R.id.menu_group:
        		showView(GROUPVIEW,currentState);
        		break;
        	case R.id.menu_medicines:
        		showView(MEDICINEVIEW,currentState);
        		break;
        	case R.id.menu_medicals:
        		showView(MEDICALVIEW,currentState);
        		break;
        	case R.id.menu_feeds:
        		showView(FEEDVIEW,currentState);
        		break;
        	case R.id.menu_add_observation:
	    		// Add a blank observation, Start a new Observation
	    		Intent intent = new Intent(BovineActivity.this, ObservationActivity.class);
	    		intent.putExtra(ITEMID, -1);
	    		intent.putExtra("data",new String[]{});
	    		startActivityForResult(intent, NEW);
	    		stack.push(currentState);
	    		//$FALL-THROUGH$
        	case R.id.menu_observation:
        		showView(BOVINEVIEW,currentState);
        		break;
        	case R.id.menu_save:
        		if(bovineView.isValid()){
	        		edit = false;
	        		
	        		Bovine b = id==-1?new Bovine((bovineView.get()[0][ViewCattleArrayAdapter.DOB].equals("")?null:new Date(Long.parseLong(bovineView.get()[0][ViewCattleArrayAdapter.DOB])))):LivestockSolutions.getBovineByID(id);
	        		Eartag e = b.getEartag()!=null? b.getEartag():new Eartag();
	        		e.setEartagID(bovineView.get()[0][ViewCattleArrayAdapter.VISUALID]);
	        		e.setNlisID(bovineView.get()[0][ViewCattleArrayAdapter.NLIS]);
	        		e.setRfID(bovineView.get()[0][ViewCattleArrayAdapter.NLISRFID]);
	        		
	        		b.setDOB(bovineView.get()[0][ViewCattleArrayAdapter.DOB].equals("")?null:new Date(Long.parseLong(bovineView.get()[0][ViewCattleArrayAdapter.DOB])));
	        		b.setEartag(e);
	        		// Assuming Birth
	        		// TODO can be changed to allow selection later.
	        		b.setAcquisition(new Acquisition("Birth", 0.00F, null));
	        		b.setBreed(LivestockSolutions.getCattleBreedByID(Long.parseLong(bovineView.get()[0][ViewCattleArrayAdapter.BREED])));
	        		Cow dame = (Cow)LivestockSolutions.getBovineByID(Long.parseLong(bovineView.get()[0][ViewCattleArrayAdapter.DAME]));
	        		if(dame != null){
	        			b.setDame(dame);
	        			this.dame=dame.getID();
	        		}
	        		Bull sire = (Bull)LivestockSolutions.getBovineByID(Long.parseLong(bovineView.get()[0][ViewCattleArrayAdapter.SIRE]));
	        		if(sire != null){
	        			b.setSire(sire);
	        			this.sire=sire.getID();
	        		}
	        		Mob mob = (Mob)LivestockSolutions.getGroupByID(Long.parseLong(bovineView.get()[0][ViewCattleArrayAdapter.MOB]));
	        		b.setMob(mob);
	        		mob = b.getBelongingMob();
	        		if(mob != null){
	        			this.mob=mob.getID();
	        		}else{
	        			this.mob=0;
	        		}
	        		String[] genderList=getResources().getStringArray(R.array.cattle_gender);
	        		if(b.getGender().equals(genderList[ViewCattleArrayAdapter.GENDER_UNKNOWN]) && !bovineView.get()[0][ViewCattleArrayAdapter.GENDER].equals(genderList[ViewCattleArrayAdapter.GENDER_UNKNOWN])){
	        			// Change our type to the correct Gender.
	        			if(bovineView.get()[0][ViewCattleArrayAdapter.GENDER].equals(genderList[ViewCattleArrayAdapter.GENDER_MALE])){
	        				b=b.setGender(Bull.class);
	        			}else if(bovineView.get()[0][ViewCattleArrayAdapter.GENDER].equals(genderList[ViewCattleArrayAdapter.GENDER_FEMALE])){
	        				b=b.setGender(Cow.class);
	        			}
	        		}
	        		id=b.getID();
	        		if(LivestockSolutions.addBovine(b)){
	        			Toast.makeText(this,getResources().getString(R.string.message_saved,getResources().getString(R.string.cattle)),Toast.LENGTH_SHORT).show();
	        		}else{
	        			Toast.makeText(this,getResources().getString(R.string.message_errorSave,getResources().getString(R.string.cattle),getResources().getString(R.string.message_unknown)),Toast.LENGTH_SHORT).show();
	        		}
	        		
	        		built=false;
	        		onPrepareOptionsMenu(menu);
	        		showView(currentState.getInt(STATEID,BOVINEVIEW),currentState);
	        		// Pop current view
	        		stack.pop();
	        		if(!stack.isEmpty()){
		        		// Pop edit change
		        		stack.pop();
	        		}
	        		break;
        		}
	        //$FALL-THROUGH$
        	default:
	            return super.frameSelection(frame);
        }
        return true;
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data){
    	if(resultCode == RESULT_OK){
    		Bovine b = LivestockSolutions.getBovineByID(id);
    		int index = data.getIntExtra(ITEMID, -1);
    		String[] returned = data.getStringArrayExtra("data");
	    	switch (requestCode){
		    	case EXISTING:
		    		// If id does not exist then there must be an error!
		    		if(index>-1){
			    		observationList.replace(returned, index);
			    		drawObservations();
			    		Observation[] bovineObservationList = b.getObservations();
			    		Observation observation = null;
			    		for(Observation o : bovineObservationList){
			    			if(o.getID() == Long.parseLong(returned[ViewObservationArrayAdapter.ID])){
			    				observation = o;
			    				observation.setComment(returned[ViewObservationArrayAdapter.VALUE]);
			    				observation.setPriority(Integer.parseInt(returned[ViewObservationArrayAdapter.TYPE]));
			    				break;
			    			}
			    		}
			    		if(observation!=null){
			    			b.addObservation(observation);
			    			LivestockSolutions.addBovine(b);
			    		}
		    		}else{
		    			Toast.makeText(this, getResources().getString(R.string.message_errorSave,R.string.observation,R.string.message_unexpectedReturn), Toast.LENGTH_SHORT).show();
		    		}
		    		break;
		    	case NEW:
		    		observationList.add(returned);
		    		index = observationList.getCount()-1;
		    		drawObservations();
    				b.addObservation(new Observation(
						new Date(Long.parseLong(returned[ViewObservationArrayAdapter.DATE])),
						returned[ViewObservationArrayAdapter.VALUE],
						Integer.parseInt(returned[ViewObservationArrayAdapter.TYPE])
					));
    				LivestockSolutions.addBovine(b);
		    		break;
	    	}
    	}
    }
	
	@Override
	public boolean constructFrame(int view) {
		if(bovineView!=null){
	    	switch (view) {
		        case JOINVIEW:
		        	setContentView(RESOURCEID[JOINVIEW]);
		        	setPage();
		        	drawJoins();
		            break;
		        case CATTLEVIEW:
		        	setContentView(RESOURCEID[CATTLEVIEW]);
		        	setPage();
		        	drawOffspring();
		            break;
		        case GROUPVIEW:
		        	setContentView(RESOURCEID[GROUPVIEW]);
		        	setPage();
		        	drawGroups();
		            break;
		        case MEDICALVIEW:
		        	setContentView(RESOURCEID[MEDICALVIEW]);
		        	setPage();
		        	drawMedicals();
		            break;
		        case MEDICINEVIEW:
		        	setContentView(RESOURCEID[MEDICINEVIEW]);
		        	setPage();
		        	drawMedicines();
		            break;
		        case FEEDVIEW:
		        	setContentView(RESOURCEID[FEEDVIEW]);
		        	setPage();
		        	drawFeeds();
		            break;
		        case BOVINEVIEW:
		        	setContentView(RESOURCEID[BOVINEVIEW]);
		        	setPage();
		        	drawObservations();
		            break;
		        default:
		            return super.constructFrame(view);
	    	}
	    	return true;
		}
		return super.constructFrame(view);
    }

	/**
     * Set up the view to show the relevant content
     */
    protected void setPage(){
    	LinearLayout itemView = (LinearLayout) findViewById(R.id.listView);
    	itemView.removeAllViews();
    	Bovine b = LivestockSolutions.getBovineByID(id);
    	if(id==-1){
        	bovineView.setNewCattle();
        }else if(edit){
        	if(b == null || b.getDob() == null || b.getGender().toLowerCase().equals(getResources().getStringArray(R.array.cattle_gender)[ViewCattleArrayAdapter.GENDER_UNKNOWN].toLowerCase())){
        		bovineView.setNewCattle();
        	}else{
        		bovineView.setModifyCattle();
        	}
        }else{
        	bovineView.setViewCattle();
        }
    	
		bovineView.setRoot(itemView);

		// Get a list of Mobs.
		Mob[] mobs = LivestockSolutions.getOnlyMobs();
		String[][] mobValues = new String[mobs.length+1][];
		
		String[] mobNone = new String[2];
		mobNone[ViewCattleArrayAdapter.ID] = String.valueOf(0);
		mobNone[ViewCattleArrayAdapter.NAME] = getResources().getString(R.string.cattle_mob_none);
		mobValues[0]=mobNone;
		
		for(int x=0; x<mobs.length; x++){
			String[] item = new String[2];
			item[ViewCattleArrayAdapter.ID] = String.valueOf(mobs[x].getID());
			item[ViewCattleArrayAdapter.NAME] = mobs[x].getName();
			
			mobValues[x+1]=item;
		}
		
		bovineView.setMobList(mobValues);
		
		// Get a list of possible Dame and Sires.
		String[] genderList=getResources().getStringArray(R.array.cattle_gender);
		Bovine[] bovines = LivestockSolutions.getBovines();
		
		ArrayList<String[]> tempBullList = new ArrayList<String[]>();
		ArrayList<String[]> tempCowList = new ArrayList<String[]>();
		
		String[] noParent = new String[2];
		noParent[ViewCattleArrayAdapter.ID]=String.valueOf(0);
		noParent[ViewCattleArrayAdapter.NAME]=getResources().getString(R.string.cattle_name_none);
		
		tempBullList.add(noParent);
		tempCowList.add(noParent);
		
		for(Bovine bovine : bovines){
			
			int days = bovine.getBreed().getGestationPeriodInDays()+30;
//				int days = bovine.getBreed().getAveragePubityAgeInDays()+bovine.getBreed().getGestationPeriodInDays()+30;
			Calendar cal = Calendar.getInstance();
				cal.add(Calendar.DATE, -days);
			Calendar ca = Calendar.getInstance();
				// Allow up to two months to allow a possible bovine to be the parents of a new offspring.
				ca.add(Calendar.DATE, bovine.getBreed().getGestationPeriodInDays()+60);
			if((bovine.getDob() == null || bovine.getDob().before(cal.getTime())) && (bovine.isActive()||bovine.getDeacquisition()!=null&&bovine.getDeacquisition().getDate().before(ca.getTime()))){
				String[] item = new String[2];
				item[ViewCattleArrayAdapter.ID]=String.valueOf(bovine.getID());
				item[ViewCattleArrayAdapter.NAME]=bovine.getEartag().getEartagID()+" - "+bovine.getEartag().getRfID();
				
				if(bovine.getGender().equals(genderList[ViewCattleArrayAdapter.GENDER_MALE])){	
					// The Bull could be a Father.
					tempBullList.add(item);
				}else if(bovine.getGender().equals(genderList[ViewCattleArrayAdapter.GENDER_FEMALE])){
					// The Cow could be the mother
					tempCowList.add(item);
				}
			}
		}
		
		bovineView.setSireList(tempBullList.toArray(new String[][]{}));
		bovineView.setDameList(tempCowList.toArray(new String[][]{}));
		
		// Get a list of possible Cattle Breeds.
		CattleBreed[] cattleBreeds = LivestockSolutions.getBreeds();
		String[][] breedValues = new String[cattleBreeds.length][];
		for(int x=0; x<cattleBreeds.length; x++){
			String[] item = new String[2];
			item[ViewCattleArrayAdapter.ID] = String.valueOf(cattleBreeds[x].getID());
			item[ViewCattleArrayAdapter.NAME] = cattleBreeds[x].getBreedName();
			
			breedValues[x]=item;
		}
		
		ViewCattleArrayAdapter.setBreedList(breedValues);
		
		View v = bovineView.getView(0,null, itemView);
		
		View d = v.findViewById(R.id.cattleDame);
		View s = v.findViewById(R.id.cattleSire);
		if(id!=-1 && b != null && ((edit && !b.getGender().toLowerCase().equals(getResources().getStringArray(R.array.cattle_gender)[ViewCattleArrayAdapter.GENDER_UNKNOWN].toLowerCase()))|| !edit)){
			d.setEnabled(dame>0);
			if(dame>0 && !edit){
	    		d.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						Intent intent = new Intent(BovineActivity.this, BovineActivity.class);
						intent.putExtra(ITEMID, dame);
				    	startActivityForResult(intent, EXISTING);
					}
				});
			}
			
			s.setEnabled(sire>0);
			if(sire>0 && !edit){
	    		s.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						Intent intent = new Intent(BovineActivity.this, BovineActivity.class);
						intent.putExtra(ITEMID, sire);
				    	startActivityForResult(intent, EXISTING);
					}
				});
			}
		}
		if(edit || id==-1){
			
		}else{
			View m = v.findViewById(R.id.cattleMOB);
			m.setEnabled(mob>0);
			if(mob>0){
	    		m.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						Intent intent = new Intent(BovineActivity.this, MobActivity.class);
						intent.putExtra(ITEMID, mob);
				    	startActivityForResult(intent, EXISTING);
					}
				});
			}
		}
    	itemView.addView(v,0);
    	
    	if(empty){
    		TextView tv = new TextView(this);
    		tv.setText((LivestockSolutions.getBreeds().length == 0 && id==-1)?getResources().getString(R.string.message_noBreed):getResources().getString(R.string.message_noData,getResources().getString(R.string.animal),id));
    		((LinearLayout)((LinearLayout)v).getChildAt(0)).removeAllViews();
    		((LinearLayout)((LinearLayout)v).getChildAt(0)).addView(tv,0);
    	}
    }
	
	/**
     * Draw the list of Observations.<br>
     * As these contain non-editable content, nothing can be in the middle of being altered.
     * So the whole list can be re-drawn to show any changes.
     */
    protected void drawObservations(){
    	setupListTitle(R.id.selectiveListTitle, R.layout.list_item_observation);
    	
    	LinearLayout view = (LinearLayout) findViewById(R.id.selectiveList);
    	view.removeAllViews();
	    if(observationList.getCount()>0){
	    	observationList.setRoot(view);
	    	for(int x=0; x< observationList.getCount(); x++){
	    		View v = observationList.getView(x, null, view);
	    		v.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						Intent intent = new Intent(BovineActivity.this, ObservationActivity.class);
						intent.putExtra("data",observationList.getItem(v.getId()));
						intent.putExtra(ITEMID, v.getId());
				    	startActivityForResult(intent, EXISTING);
					}
				});
	    		view.addView(v,x);
	    	}
	    }else{
	    	view.addView(inflateLayout(R.layout.item_none,view));
    	}
    }
	
    /**
     * Draw the list of Joins that belong in this Bovine.<br>
     * As these contain non-editable content, nothing can be in the middle of being altered.
     * So the whole list can be re-drawn to show any changes.
     */
    protected void drawJoins(){
    	setupListTitle(R.id.selectiveListTitle, R.layout.list_item_join);

    	LinearLayout view = (LinearLayout) findViewById(R.id.selectiveList);
    	view.removeAllViews();
    	if(joinList.getCount()>0){
	    	joinList.setRoot(view);
	    	for(int x=0; x< joinList.getCount(); x++){
	    		View v = joinList.getView(x, null, view);
	    		v.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						Intent intent = new Intent(BovineActivity.this, JoinActivity.class);
						intent.putExtra(ITEMID, Long.parseLong(joinList.getItem(v.getId())[ViewJoinArrayAdapter.ID]));
				    	startActivityForResult(intent, EXISTING);
					}
				});
	    		view.addView(v,x);
	    	}
	    }else{
	    	view.addView(inflateLayout(R.layout.item_none,view));
		}
    }
    
    /**
     * Draw the list of Offspring that are from this Bovine.<br>
     * As these contain non-editable content, nothing can be in the middle of being altered.
     * So the whole list can be re-drawn to show any changes.
     */
    protected void drawOffspring(){
    	setupListTitle(R.id.selectiveListTitle, R.layout.list_item_cattle);
    	((TextView)((LinearLayout)findViewById(R.id.selectiveListTitle)).findViewById(R.id.title)).setText(getResources().getString(R.string.menu_offspring));
    	
    	LinearLayout view = (LinearLayout) findViewById(R.id.selectiveList);
    	view.removeAllViews();
    	if(cattleList.getCount()>0){
	    	cattleList.setRoot(view);
	    	for(int x=0; x< cattleList.getCount(); x++){
	    		View v = cattleList.getView(x, null, view);
	    		v.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						Intent intent = new Intent(BovineActivity.this, BovineActivity.class);
						intent.putExtra(ITEMID, Long.parseLong(cattleList.getItem(v.getId())[ViewCattleArrayAdapter.ID]));
				    	startActivityForResult(intent, EXISTING);
					}
				});
	    		view.addView(v,x);
	    	}
	    }else{
	    	view.addView(inflateLayout(R.layout.item_none,view));
		}
    }
    
    /**
     * Draw the list of Groups that this Bovine belong to.<br>
     * As these contain non-editable content, nothing can be in the middle of being altered.
     * So the whole list can be re-drawn to show any changes.
     */
    protected void drawGroups(){
    	setupListTitle(R.id.selectiveListTitle, R.layout.list_item_group);
    	
    	LinearLayout view = (LinearLayout) findViewById(R.id.selectiveList);
    	view.removeAllViews();
    	if(groupList.getCount()>0){
	    	groupList.setRoot(view);
	    	for(int x=0; x< groupList.getCount(); x++){
	    		View v = groupList.getView(x, null, view);
	    		v.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						Intent intent = new Intent(BovineActivity.this, GroupActivity.class);
						intent.putExtra(ITEMID, Long.parseLong(groupList.getItem(v.getId())[ViewGroupMobArrayAdapter.ID]));
				    	startActivityForResult(intent, EXISTING);
					}
				});
	    		view.addView(v,x);
	    	}
	    }else{
	    	view.addView(inflateLayout(R.layout.item_none,view));
		}
    }
    
    /**
     * Draw the list of Feed that this Bovine has consumed that has been purchased.<br>
     * As these contain non-editable content, nothing can be in the middle of being altered.
     * So the whole list can be re-drawn to show any changes.
     */
	private void drawFeeds() {
		setupListTitle(R.id.selectiveListTitle, R.layout.list_item_usableitemhistory);
    	((TextView)findViewById(R.id.title)).setText(getResources().getString(R.string.list_item_feed));
    	LinearLayout view = (LinearLayout) findViewById(R.id.selectiveList);
    	view.removeAllViews();
    	if(feedList.getCount()>0){
	    	feedList.setRoot(view);
	    	for(int x=0; x< feedList.getCount(); x++){
	    		View v = feedList.getView(x, null, view);
	    		v.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						Intent intent = new Intent(BovineActivity.this, FeedActivity.class);
						intent.putExtra(ITEMID, Long.parseLong(feedList.getItem(v.getId())[ListUsableItemHistoryArrayAdapter.ID]));
				    	startActivityForResult(intent, EXISTING);
					}
				});
	    		view.addView(v,x);
	    	}
		}else{
	    	view.addView(inflateLayout(R.layout.item_none,view));
		}
	}

	/**
     * Draw the list of Medicines that have been used on this Bovine.<br>
     * As these contain non-editable content, nothing can be in the middle of being altered.
     * So the whole list can be re-drawn to show any changes.
     */
	private void drawMedicines() {
		setupListTitle(R.id.selectiveListTitle, R.layout.list_item_usableitemhistory);
    	((TextView)findViewById(R.id.title)).setText(getResources().getString(R.string.menu_medicine));
    	LinearLayout view = (LinearLayout) findViewById(R.id.selectiveList);
    	view.removeAllViews();
    	if(medicineList.getCount()>0){
	    	medicineList.setRoot(view);
	    	for(int x=0; x< medicineList.getCount(); x++){
	    		View v = medicineList.getView(x, null, view);
	    		v.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						Intent intent = new Intent(BovineActivity.this, ChemicineActivity.class);
						intent.putExtra(ITEMID, Long.parseLong(medicineList.getItem(v.getId())[ListUsableItemHistoryArrayAdapter.ID]));
				    	startActivityForResult(intent, EXISTING);
					}
				});
	    		view.addView(v,x);
	    	}
		}else{
	    	view.addView(inflateLayout(R.layout.item_none,view));
		}
	}

	/**
     * Draw the list of Vet Visits for this Bovine.<br>
     * As these contain non-editable content, nothing can be in the middle of being altered.
     * So the whole list can be re-drawn to show any changes.
     */
	private void drawMedicals() {
		setupListTitle(R.id.selectiveListTitle, R.layout.list_item_usableitemhistory);
    	((TextView)findViewById(R.id.title)).setText(getResources().getString(R.string.medical));
    	LinearLayout view = (LinearLayout) findViewById(R.id.selectiveList);
    	view.removeAllViews();
    	
    	// Get a list of possible Businesses
		Business[] businesses = LivestockSolutions.getOnlyBusinesses();
		String[][] businessList = new String[businesses.length][];
		
		for(int x=0; x<businesses.length; x++){
			String[] item = new String[2];
			item[ViewCattleArrayAdapter.ID]=String.valueOf(businesses[x].getID());
			item[ViewCattleArrayAdapter.NAME]=businesses[x].getName();
			businessList[x]=item;
		}
		medicalList.setOwnerList(businessList);
		if(medicalList.getCount()>0){
	    	medicalList.setRoot(view);
	    	MedicalHistory[] medicals = LivestockSolutions.getBovineByID(id).getMedicals();
	    	for(int x=0; x< medicalList.getCount(); x++){
	    		View v = medicalList.getView(x, null, view);
	    		if(edit || id==-1){
					
				}else{
					View d = v.findViewById(R.id.medicalVet);
					final long vet = Long.parseLong(medicalList.get()[x][ListMedicalHistoryArrayAdapter.ID]);
					d.setEnabled(vet>0);
					if(vet>0){
			    		d.setOnClickListener(new View.OnClickListener() {
							public void onClick(View v) {
								Intent intent = new Intent(BovineActivity.this, OwnerActivity.class);
								intent.putExtra(ITEMID, vet);
						    	startActivityForResult(intent, EXISTING);
							}
						});
					}
				}
	    		LinearLayout list = (LinearLayout) v.findViewById(R.id.medicineList);
		    	list.removeAllViews();
		    	
		    	MedicineHistory[] medicines = medicals[x].getPrescribedMedicines();
		    	Arrays.sort(medicines, usableItemHistoryComparator);
	    		String[][] medcine = new String[medicines.length][ListUsableItemHistoryArrayAdapter.SIZE];
	    		for(int z=0; z<medicines.length; z++){
	    			medcine[z][ListUsableItemHistoryArrayAdapter.ID]=String.valueOf(medicines[z].getItem().getID());
	    			medcine[z][ListUsableItemHistoryArrayAdapter.NAME]=medicines[z].getItem().getName();
	    			medcine[z][ListUsableItemHistoryArrayAdapter.USEDATE]=String.valueOf(medicines[z].getDate()!=null?medicines[z].getDate().getTime():0);
	    			medcine[z][ListUsableItemHistoryArrayAdapter.QUANTITY]=String.valueOf(medicines[z].getQuantity());
	    			medcine[z][ListUsableItemHistoryArrayAdapter.MEASUREMENT]=medicines[z].getMeasurement();
	    		}
		    	
		    	if(medicines.length>0){
		    		final ListUsableItemHistoryArrayAdapter medicineList = new ListUsableItemHistoryArrayAdapter(this, medcine);
		        	medicineList.setRoot(list);
		        	for(int y=0; y< medicineList.getCount(); y++){
		        		View m = medicineList.getView(y, null, list);
		        		m.setOnClickListener(new View.OnClickListener() {
		    				public void onClick(View m) {
		    					Intent intent = new Intent(BovineActivity.this, ChemicineActivity.class);
		    					intent.putExtra(ITEMID, Long.parseLong(medicineList.getItem(m.getId())[ListUsableItemHistoryArrayAdapter.ID]));
		    			    	startActivityForResult(intent, EXISTING);
		    				}
		    			});
		        		list.addView(m,y);
		        	}
		    	}else{
		    		list.addView(inflateLayout(R.layout.item_none,list));
		 		}
	    		view.addView(v,x);
	    	}
		}else{
    		view.addView(inflateLayout(R.layout.item_none,view));
 		}
	}
}
